const router = require('express').Router()
const { query, getTableNames } = require('../../tsp/table')

// 校验method参数
router.param('name', (req, res, next, name) => {
  const tableNames = getTableNames()
  if (!tableNames.includes(name)) {
    next(new Error(`不支持表名: ${name} . 请替换成 ${tableNames.toString()}`))
  } else {
    req.name = name
    next()
  }
})

router.get('/:name', async(req, res) => {
  const { name } = req.params
  const { env } = req.query

  const envMapper = {
    'mirror': 0,
    'prod': 1
  }
  if (env !== undefined) {
    const tmpEnv = envMapper[`${env}`.toLowerCase()]
    if (tmpEnv !== undefined) {
      res.send(await query(name, `env = ${tmpEnv}`))
      return
    }
  }
  res.send(await query(name))
})

module.exports = router
